var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myblog';
var article;
var num;
var data = {};
MongoClient.connect(url, function(err, db) {
	if(!err){
		article = db.collection('article');
	}
});
MongoClient.connect(url, function(err, db) {
  if(!err){
    num = db.collection('id');
  }
});

/* GET home page. */
router.get('/', function(req, res, next) {  
  res.render('index', { title: '欢迎您的到来' });
});

router.get('/cat', function(req, res, next) {
  res.render('cat', {  });
});
//获取数据处理
router.post('/cat', function(req, res, next) {
  num.find({_id:'num'}).toArray(function(err, docs) {//寻找到num表中的数据
    if(err){
      console.log(err);
    }else{ 
      var time = getNowFormatDate();
      req.body._id = docs[0].id;//增加累加的主键
      req.body.time = time;//设置发表的时间
      article.insert(req.body);//向article中添加数据;
      var n = docs[0].id;//[{_id:"nums",id:5}]4 number 
      var a = n+1;
      num.updateOne({ id : n },{ $set: { id : a } }, function(err, result) {//操控mongodb 修改num表中的id值
        if(err){
          console.log(err);
        }
      });
      res.redirect('/show');//路由从定向
    }	
});
});
/*处理删除文件路由*/
router.get('/del', function(req, res, next) {
  var q = parseInt(req.query.id);
   article.deleteOne({_id:q}, function(err, result) { //根据主键_id寻找到我们要删除的那一行
   if(err){
    console.log(err);
   }    
  res.redirect('/show');//删除后在从新定向到show显示界面;
  });
});
//这里是显示界面处理
router.get('/show', function(req, res, next) {	
  article.find({}).toArray(function(err, docs) {//选找到article表中的所有数据并转换为索引数组
  	if(err){
  		console.log(err);
      res.send('err');
  	}else{  	
    	data.cent = docs;//data=>{cent:[{_id:2,title:....},{_id:3,title:....}]}
    	// console.log(docs);
		  res.render('show', data);
    	//console.log(cent);
    }
  }); 
});
//更改界面
router.get('/articleshow', function(req, res, next) {//从新编辑页面
    var q = parseInt(req.query.id);//老办法通过地址栏获取主键方便寻找
    article.find({_id:q}).toArray(function(err, docs) {//根据获取到的主键找到我们需要的内容
    if(err){//如果失败
      console.log(err);//打印出来错误
    }else{//否则
      data.article = docs;//将从数据库中找到的值赋值给data下面的article
      res.render('articleshow',data);//这里将data返回给页面,express会自动读取data,此时data.article=>[{_id:11,title:'第一次测试'.....}]里面是这样子的内容, 因此在页面写article[0]就是里面存储的数据了!直接<%- 就可以读出来我们需要的值了%>
    }
  });
});
router.post('/articleshow', function(req, res, next) {
  var time = getNowFormatDate();
  var q = parseInt(req.query.id);
  req.body.time = time;
  article.updateOne({ _id : q },{ $set: req.body }, function(err, result) {//操控mongodb 修改num表中的id值
    if(err){
      console.log('err');
    }
    else{
      res.redirect('/show');
    }
  });
});
/*获取时间函数 用来设置发表的时间*/
function getNowFormatDate() { 
    var date = new Date();   
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var min = date.getMinutes();
    var sec = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (min >= 1 && min <= 9) {
        min = "0" + min;
    }
    if (sec >= 1 && sec <= 9) {
        sec = "0" + sec;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + min+ seperator2 + sec;
    return currentdate;
}
module.exports = router;
